<template>
  <div class="main-container">

    <!-- 列表 -->
    <FTable ref="tableRef" @register="register">
      <template #header-left>
        <el-button v-permission:1101="$route.meta.auth" type="primary" @click="handleAdd">{{ t('add') }}</el-button>
        <el-button v-permission:1102="$route.meta.auth" @click="handleAdd">{{ t('deleteBatch') }}</el-button>
      </template>
      <template #status="scope">
        <el-switch
          :active-value="$convert(1, scope.row.status)"
          :inactive-value="$convert(0, scope.row.status)"
          :model-value="scope.row.status"
          disabled
        />
      </template>
      <template #statistics="scope">
        <p>活动观看人数：<span class="text-[red]">{{ scope.row.guankan_num||0 }}</span> 人</p>
        <p>{{t('table.dati_num')}}<span class="text-[red]">{{ scope.row.dati_num||0 }}</span> {{t('table.dati_num.unit')}}</p>
        <p>{{t('table.hongbao_num')}}<span class="text-[red]">{{ scope.row.hongbao_num||0 }}</span> {{t('table.hongbao_num.unit')}}</p>
        <p>{{t('table.hongbao_money')}}<span class="text-[red]">{{ scope.row.hongbao_money||0 }}</span> {{t('table.hongbao_money.unit')}}</p>
        <p>{{t('table.xuefen_num')}}<span class="text-[red]">{{ scope.row.xuefen_num||0 }}</span> {{t('table.xuefen_num.unit')}}</p>
      </template>

      <template #action="{ row }">
        <el-space wrap>
          <el-button
            type="primary"
            link
            @click="handleViewData(row)"
            >活动统计</el-button
          >

          <!-- <el-button type="primary" link @click="handleEdit(row)">{{ t('opt.commentRecord') }}</el-button> -->
          <el-button type="primary" link @click="handleShowQrcode(row)">{{ t('opt.activityLink') }}</el-button>
          <el-button v-permission:1103="$route.meta.auth" type="primary" link @click="handleEdit(row)">{{ t('edit') }}</el-button>
          <el-button
            v-permission:1006="$route.meta.auth"
            type="primary"
            link
            @click="handleCopyBatch(row)"
            >{{ t("copy") }}</el-button
          >
          <el-button v-permission:1105="$route.meta.auth" type="primary" link @click="handleProblem(row)">{{ t('opt.issuesList') }}</el-button>
          <el-button v-permission:1105="$route.meta.auth" type="primary" link @click="handleChat(row)">聊天记录</el-button>
          <el-button v-permission:1107="$route.meta.auth" type="primary" link @click="handleViewMonitoring(row)">直播中台</el-button>
          <el-button v-permission:1104="$route.meta.auth" type="danger" link @click="handleDelete(row)">{{ t('delete') }}</el-button>
        </el-space>
      </template>
    </FTable>
    <f-form-model
      ref="formModelRef"
      :is="formModelName"
      v-bind="formModeProps"
      @change="() => methods.reload()"></f-form-model>

    <f-detail-drawer
      ref="detailDrawerRef"
      size="80%"
      is="ActivityDataDetail"></f-detail-drawer>
  </div>
</template>

<script lang="ts" setup>
import FFormModel from '@/addon/htscrm/components/f-form-model'
import { computed, ref, getCurrentInstance, onMounted } from 'vue'
import { t } from '@/lang'
import { useRouter } from 'vue-router'
import FTable, { BasicColumn, useTable } from '@/addon/htscrm/components/f-table'
import { tableColumns, tableSearchFormItems } from '@/addon/htscrm/data/activity.live.list'
import { deleteActivityApi, getActivityListApi } from '@/addon/htscrm/api/activity'
import { ElMessage, ElMessageBox } from 'element-plus'
import FDetailDrawer from '@/addon/htscrm/components/f-detail-drawer'

const instance = getCurrentInstance() as any
const { $convert } = instance?.appContext.config.globalProperties || {}

const router = useRouter()
const formModelRef = ref()
const formModelName = ref('ActivityCopyForm')
const detailDrawerRef = ref()

const formModeProps = computed(() => {
    return {
        showCancel: formModelName.value == 'ActivityCopyForm',
        fullscreen: formModelName.value == 'ActivityCopyForm',
        width: formModelName.value == 'ActivityCopyForm' ? 1200 : 600
    }
})

const tableRef = ref()
const { methods, register } = useTable({
    rowKey: 'id',
    searchFromItems: tableSearchFormItems(t),
    columns: tableColumns(t) as BasicColumn<any>[],
    beforeFetch: (opt) => {
        ``
        const params = JSON.parse(localStorage.getItem('liveParams') || '{}')

        paginationState.value.currentPage = opt.page || 1
        paginationState.value.pageSize = opt.limit || 10
        localStorage.removeItem('liveParams')
        return {
            page: params.page && Number(params.page) > 1 ? Number(params.page) : opt.page,
            limit: params.size && Number(params.size) > 10 ? Number(params.size) : opt.limit,
            title: opt.title || params.title || '',
            type: 2
        }
    },
    api: async (opt) => (await getActivityListApi(opt)).data
})

const paginationState = ref({
    currentPage: 1,
    pageSize: 10
})

/**
 * 新增
 */
function handleAdd () {
    router.push('/htscrm/activity/live/add')
}

/**
 * 编辑
 */
function handleEdit (row: IActivityItem) {
    handleRouter()
    router.push({
        path: '/htscrm/activity/live/edit',
        query: {
            id: row.id
        }
    })
}
function handleViewMonitoring (row: IActivityItem) {
  window.open('/monitoring/' + row.id)
}

function handleViewData (row: IActivityItem) {
    detailDrawerRef.value.show('活动统计', row)
}

/**
 * @description 删除数据
 */
async function handleDelete (row: IActivityItem) {
    const action = await ElMessageBox.alert(t('deleteTips'), t('alert.title'), {
        type: 'warning',
        showCancelButton: true,
        cancelButtonText: t('alert.cancel'),
        confirmButtonText: t('alert.confirm')
    })
    if (action === 'confirm') {
        await deleteActivityApi(row.id)
        ElMessage.success(t('deleteSuccess'))
        methods.reload()
    }
}

/**
 * 问题列表
 */
function handleProblem (row: IActivityItem) {
    router.push({
        path: '/htscrm/activity/problem',
        query: {
            id: row.id
        }
    })
}

/**
 * 聊天记录
 */
function handleChat (row: IActivityItem) {
    handleRouter()
    router.push({
        path: '/htscrm/activity/chat',
        query: {
            id: row.id
        }
    })
}
/**
 * @description 批量复制
 */
function handleCopyBatch (row?:IActivityItem) {
    const selection:IActivityItem[] = row ? [row] : methods.getSelectionRows()
    if (selection.length == 0) {
        ElMessage.warning(t('copyBatchTips'))
        return
    }
    formModelName.value = 'ActivityCopyForm'
    setTimeout(() => {
        formModelRef.value.show('批量复制', selection, 1)
    }, 10)
}

function handleShowQrcode (row:IActivityItem) {
    formModelName.value = 'ActivityQrcodeForm'

    setTimeout(() => {
        formModelRef.value.show('活动链接', row)
    }, 10)
}

/**
 * 保存搜索信息
 */
function handleRouter () {
    const params = {
        page: paginationState.value.currentPage,
        size: paginationState.value.pageSize,
        title: methods.getSearchInfo().title || ''
    }
    localStorage.setItem('liveParams', JSON.stringify(params))
}

onMounted(() => {
    const params = JSON.parse(localStorage.getItem('liveParams') || '{}')
    if (params.title) {
        methods.setFormData({
            title: params.title
        })
    }

    methods.reload({
        page: params.page && Number(params.page) > 1 ? Number(params.page) : 1
    })
})
</script>
